package com.achun.getcouponleague.ui.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.achun.getcouponleague.Bean.CategoriesContent;
import com.achun.getcouponleague.Bean.Category;
import com.achun.getcouponleague.Bean.TiketBody;
import com.achun.getcouponleague.R;
import com.achun.getcouponleague.base.BaseFragment;
import com.achun.getcouponleague.base.IRecyclerList;
import com.achun.getcouponleague.base.LooperViewpageAdapter;
import com.achun.getcouponleague.presenter.impl.CategoryPagePresenter;
import com.achun.getcouponleague.presenter.impl.TiketPresenter;
import com.achun.getcouponleague.ui.activity.TiketActivity;
import com.achun.getcouponleague.ui.adapter.RecycleviewAdapter;
import com.achun.getcouponleague.ui.custom.LoopViewPager;
import com.achun.getcouponleague.utils.Constant;
import com.achun.getcouponleague.utils.Logutils;
import com.achun.getcouponleague.utils.PresenterManager;
import com.achun.getcouponleague.utils.UIutils;
import com.achun.getcouponleague.view.ICategoryPageViewCallback;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TbNestedScrollView;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.List;

import butterknife.BindView;

public class HomePagerFragment extends BaseFragment implements ICategoryPageViewCallback {

    private TextView title_tv;
    private CategoryPagePresenter categoryPagePresenter;
    private int materialId;

    @BindView(R.id.recycle_view)
    public RecyclerView recycle_view;
    private RecycleviewAdapter recycleviewAdapter;
    @BindView(R.id.looper_page_view)
    public LoopViewPager looper_page_view;
    private LooperViewpageAdapter looperViewpageAdapter;
    @BindView(R.id.layout_indicator_view)
    public LinearLayout layout_indicator;
    private GradientDrawable selectDrawable;
    private GradientDrawable normalDrawable;
    @BindView(R.id.homePageParent)
    public RelativeLayout homePageParent;
    @BindView(R.id.tbNestedScrollView)
    public TbNestedScrollView tbNestedScrollView;
    @BindView(R.id.tw_refresh_view)
    public TwinklingRefreshLayout twRefreshView;
    @BindView(R.id.category_title_tv)
    public TextView category_title;
    private TiketPresenter tiketPresenter;
    private String title;


    //获取fragment对象
    public static HomePagerFragment newInstance(Category.DataBean category) {
        HomePagerFragment homePagerFragment = new HomePagerFragment();
        Bundle bundle = new Bundle();
        bundle.putString(Constant.KEY_HOME_PAGER_TITLE, category.getTitle());
        bundle.putInt(Constant.KEY_HOME_PAGER_MATERIALID, category.getId());
        homePagerFragment.setArguments(bundle);
        return homePagerFragment;
    }

    @Override
    public View loadSuccessView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home_pager, container, false);
    }

    @Override
    protected void initView(View rootview) {
        //设置recycleview布局管理器
        recycle_view.setLayoutManager(new LinearLayoutManager(getContext()));
        recycle_view.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = 10;
                outRect.bottom = 10;
                outRect.left = 10;
                outRect.right = 10;
            }
        });
        //设置设配器
        recycleviewAdapter = new RecycleviewAdapter();
        recycle_view.setAdapter(recycleviewAdapter);
        //轮播图适配器
        looperViewpageAdapter = new LooperViewpageAdapter();
        looper_page_view.setAdapter(looperViewpageAdapter);

        //禁止上拉加载
        twRefreshView.setEnableRefresh(false);





    }

    @Override
    public void onResume() {
        Logutils.e(this.getClass(),"resume...");
        super.onResume();
        looper_page_view.startLoop();
    }

    @Override
    public void onPause() {
        Logutils.e(this.getClass(),"pause...");
        super.onPause();
        looper_page_view.endLoop();
    }
    //处理跳转事件
    private void handleclick(IRecyclerList item){
        String coupon_share_url = "https:"+item.getCoupon_share_url();
        String title = item.getTitle();
        String cover = item.getPict_url();
        tiketPresenter.createTiketCode(coupon_share_url,title,cover);
        Intent intent = new Intent(getContext(), TiketActivity.class);
        startActivity(intent);
    }
    //初始化事件
    @Override
    protected void initListener() {
        //recycleview点击事件
        recycleviewAdapter.setRecycleViewOnClickListener(new RecycleviewAdapter.RecycleViewOnClickListener() {
            @Override
            public void onclick(int position, IRecyclerList item) {
               handleclick(item);
            }
        });

        //轮播图点击事件
        looperViewpageAdapter.setLooperClicklistener(new LooperViewpageAdapter.LooperClicklistener() {
            @Override
            public void onClick(int position, CategoriesContent.DataBean item) {
                handleclick(item);
            }
        });

        //加载更多监听事件
        twRefreshView.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {

            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
               categoryPagePresenter.loadingMore(materialId);
            }
        });
//        外布局的监听事件
        homePageParent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //设置父滑动消费距离
                int loopViewpageHeight = looper_page_view.getMeasuredHeight();
                tbNestedScrollView.setHeadHeight(loopViewpageHeight);

                int measuredHeight = homePageParent.getMeasuredHeight();
                Logutils.d(this.getClass(),"relativelayout_height--"+measuredHeight);
                ViewGroup.LayoutParams layoutParams = recycle_view.getLayoutParams();
                layoutParams.height=measuredHeight;
                recycle_view.setLayoutParams(layoutParams);
                //只调用一次就结束这个回调
                if(measuredHeight!=0){
                    homePageParent.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });

        looper_page_view.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (looperViewpageAdapter.getDataSize()!=0) {
                    int targetposition = position % looperViewpageAdapter.getDataSize();
                    //更新指示器
                    updateIndicator(targetposition);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void onReTry() {
        loadData();
    }

    private void updateIndicator(int targetposition) {
        for (int i = 0; i <layout_indicator.getChildCount(); i++) {
            View childAt = layout_indicator.getChildAt(i);
            if (targetposition==i){
                childAt.setBackgroundResource(R.drawable.shape_indicator_back_selected);
            }else {
                childAt.setBackgroundResource(R.drawable.shape_indicator_back_normal);
            }

        }
    }

    @Override
    protected void initPresenter() {
        categoryPagePresenter = CategoryPagePresenter.getInstance();
        categoryPagePresenter.registerCallback(this);
        tiketPresenter = PresenterManager.getInstance().getTiketPresenter();
    }

    @Override
    protected void release() {
        categoryPagePresenter.unRegisterCallback(this);
    }

    @Override
    protected void loadData() {
        setViewStatus(Status.SUCCESS);
        Bundle bundle = getArguments();
        title = bundle.getString(Constant.KEY_HOME_PAGER_TITLE);
        category_title.setText(title);
        materialId = bundle.getInt(Constant.KEY_HOME_PAGER_MATERIALID);
        Logutils.e(this.getClass(), "title-->" + title + "materialId-->" + materialId);
        if (categoryPagePresenter != null) {
            categoryPagePresenter.getContentByCategroyId(materialId);
        }


    }

    @Override
    public int getCategoryId() {
        return materialId;
    }

    @Override
    public void onCOntentLoaded(List<CategoriesContent.DataBean> categorypagelist) {
        setViewStatus(Status.SUCCESS);
        recycleviewAdapter.setDatas(categorypagelist);

    }

    @Override
    public void onLoading() {
        setViewStatus(Status.LOADING);
    }

    @Override
    public void onError() {
        setViewStatus(Status.ERROR);

    }

    @Override
    public void onEmpty() {
        setViewStatus(Status.EMPTY);
    }

    @Override
    public void onLoadMoreError() {
        Toast.makeText(getContext(),"网络错误，请稍后重试",Toast.LENGTH_SHORT).show();
        twRefreshView.finishLoadmore();
    }

    @Override
    public void onLoadMoreEmpty() {

    }

    @Override
    public void onLoadMoreLoaded(List<CategoriesContent.DataBean> categorypagelist) {
        Logutils.e(this.getClass(),"加载了--》"+categorypagelist);
        recycleviewAdapter.addDatas(categorypagelist);
        Toast.makeText(getContext(),"为您加载了"+categorypagelist.size()+"条数据",Toast.LENGTH_SHORT).show();
        twRefreshView.finishLoadmore();
    }

    @Override
    public void onLooperListLoaded(List<CategoriesContent.DataBean> categorypagelist) {
        Logutils.e(this.getClass(), "轮播图监听");
        looperViewpageAdapter.setdatas(categorypagelist);
        //设置指示器
        layout_indicator.removeAllViews();
        selectDrawable = (GradientDrawable) getContext().getDrawable(R.drawable.shape_indicator_back_selected);
        normalDrawable = (GradientDrawable) getContext().getDrawable(R.drawable.shape_indicator_back_normal);

        int size= UIutils.dip2px(getContext(),10);
        for (int i = 0; i < categorypagelist.size(); i++) {
            View view = new View(getContext());
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(size, size);
            layoutParams.leftMargin=UIutils.dip2px(getContext(),5);
            layoutParams.rightMargin=UIutils.dip2px(getContext(),5);
            view.setLayoutParams(layoutParams);
            view.setBackground(normalDrawable);
            layout_indicator.addView(view);

        }
        int dex=Integer.MAX_VALUE/2%categorypagelist.size();//与第0个的差值
        looper_page_view.setCurrentItem(Integer.MAX_VALUE/2-dex);

    }
}
